<template>
  <div class="analysis-page-root bg-dark text-light p-3">
    <h4 class="mb-3">指数智能分析</h4>

    <!-- 控制区域：指数选择、自定义日期区间 -->
    <div class="row m-0 p-0 align-items-center mb-3">
      <div class="col p-0 d-flex align-items-center position-relative me-3">
        <label class="me-2">选择指数：</label>
        <div class="selected-tags-container me-2" @click="showDropdown = !showDropdown">
          <span v-if="selectedCodes.length === 0">请选择指数</span>
          <span v-else>
            {{ selectedCodes.map(code => allIndexOptions.find(o => o.ts_code === code)?.name || code).join('，') }}
          </span>
           <span class="dropdown-toggle-icon">{{ showDropdown ? '▲' : '▼' }}</span>
        </div>
         <button class="btn btn-primary" @click="fetchCustomAnalysis">分析所选区间</button>

        <!-- 弹出式多选菜单 -->
        <div v-if="showDropdown" class="dropdown-menu-custom bg-dark border-secondary p-2">
          <div class="dropdown-item-custom" v-for="item in allIndexOptions" :key="item.ts_code">
            <input type="checkbox" :value="item.ts_code" v-model="selectedCodes" :id="'chk-analysis-' + item.ts_code">
            <label :for="'chk-analysis-' + item.ts_code">{{ item.name }} ({{ item.ts_code }})</label>
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义日期区间分析控制区域 -->
    <div class="row m-0 p-0 mt-2 align-items-center mb-3">
        <div class="col-auto p-0 me-2">
            <label>自定义分析区间：</label>
        </div>
        <div class="col-auto p-0 me-2">
            <input type="date" class="form-control form-control-sm bg-dark text-light border-secondary" v-model="customStartDate">
        </div>
         <div class="col-auto p-0 me-2">
            至
        </div>
        <div class="col-auto p-0 me-2">
             <input type="date" class="form-control form-control-sm bg-dark text-light border-secondary" v-model="customEndDate">
        </div>
    </div>

    <!-- 智能分析结果区域 -->
    <div v-if="analysisResults.length" class="analysis-area mt-3 p-3 bg-secondary rounded">
      <h6 class="text-primary">智能分析结果：</h6>
      <div v-for="result in analysisResults" :key="result.code" class="mb-3">
        <p class="mb-1"><strong>{{ result.name || result.code }}：</strong></p>
        <ul>
          <li v-for="item in filteredAnalysisItems(result.analysis_items)" :key="item.label" class="mb-1">
            <strong>{{ item.label }}:</strong> {{ item.value }}
          </li>
        </ul>
      </div>
    </div>

     <div v-else-if="selectedCodes.length && customStartDate && customEndDate" class="analysis-area mt-3 p-3 bg-secondary rounded">
         <p>点击 "分析所选区间" 获取结果...</p>
     </div>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

const allIndexOptions = [
  { name: '沪深300', ts_code: '399300.SZ' },
  { name: '上证指数', ts_code: '000001.SH' },
  { name: '深证成指', ts_code: '399001.SZ' },
  { name: '上证50', ts_code: '000016.SH' },
  { name: '中证1000', ts_code: '000852.SH' },
  { name: '中证500', ts_code: '399905.SZ' },
  { name: '中证A50', ts_code: '000922.SH' }
]; // Keep this list here for index selection

const selectedCodes = ref([]); // 叠加对比指数
const showDropdown = ref(false); // 控制下拉菜单显示隐藏

const analysisResults = ref([]); // 用于存储结构化分析结果

const customStartDate = ref(null); // 自定义分析开始日期
const customEndDate = ref(null); // 自定义分析结束日期

// Computed property to filter analysis items
const filteredAnalysisItems = computed(() => (items) => {
  const allowedLabels = ['分析']; // Only include '分析'
  if (!Array.isArray(items)) {
    return []; // Return an empty array if items is not an array
  }
  return items.filter(item => allowedLabels.includes(item.label));
});

// 函数：获取自定义日期区间的智能分析
const fetchCustomAnalysis = async () => {
    console.log('Fetching custom analysis for codes:', selectedCodes.value.join(','), 'range:', customStartDate.value, 'to', customEndDate.value);

    if (!selectedCodes.value.length) {
        analysisResults.value = [{ code: 'info', name: '提示', analysis: '请先选择需要分析的指数。' }];
        return;
    }
     if (!customStartDate.value || !customEndDate.value) {
         analysisResults.value = [{ code: 'info', name: '提示', analysis: '请选择自定义分析区间的起始日期和结束日期。' }];
         return;
     }
     if (new Date(customStartDate.value) > new Date(customEndDate.value)) {
          analysisResults.value = [{ code: 'info', name: '提示', analysis: '起始日期不能晚于结束日期。' }];
          return;
     }

    try {
        // 调用后端分析接口，传递自定义日期范围和当前的时间区间类型
        // 注意：这里需要一个默认或可选择的 interval 参数，暂时使用 '1W' 作为默认值
        const analyzeRes = await axios.get('/api/v1/index/analyze', {
           params: {
              codes: selectedCodes.value.join(','),
              interval: '1W', //  TODO: Consider adding interval selection to the analysis page
              start_date: customStartDate.value, // 传递自定义开始日期
              end_date: customEndDate.value // 传递自定义结束日期
           }
        });

        if (analyzeRes.data.code === 200) {
           console.log('Custom analysis data fetched successfully:', analyzeRes.data.data);
           analysisResults.value = analyzeRes.data.data; // Update with structured data
        } else {
           console.error('Failed to fetch custom analysis data:', analyzeRes.data.message);
           analysisResults.value = [{ code: 'error', name: '错误', analysis: `分析失败：${analyzeRes.data.message}` }];
        }
    } catch (error) {
      console.error('Error fetching custom analysis data:', error);
       analysisResults.value = [{ code: 'error', name: '错误', analysis: `分析请求出错：${error.message}` }];
    }
};

// 点击外部关闭下拉菜单
onMounted(() => {
  document.addEventListener('click', (e) => {
    // Use a more specific selector to target the dropdown container in this component
    const dropdownContainer = document.querySelector('.analysis-page-root .col.p-0.d-flex.align-items-center.position-relative');
    if (dropdownContainer && !dropdownContainer.contains(e.target)) {
      console.log('Clicked outside analysis dropdown, closing.');
      showDropdown.value = false;
    }
  });
});

</script>

<style scoped>
/* 可以复制 IndexDashboard.vue 中的相关样式或根据需要调整 */
.analysis-page-root {
  /* 基本布局和颜色 */
  width: 100%;
  height: 100%;
  background: #181A20; /* Reverted to dark background */
  padding: 20px;
  color: #ecf0f1; /* Reverted to light text */
}

.selected-tags-container {
    border: 1px solid #444; /* Reverted to dark border */
    border-radius: 0.25rem;
    padding: 0.375rem 0.75rem;
    min-height: 38px; /* 保持与按钮对齐 */
    cursor: pointer;
    background-color: #242424; /* Reverted to dark background */
    color: #e0e0e0; /* Reverted to light text */
    flex-grow: 1; /* 占据剩余空间 */
    display: flex;
    align-items: center;
     position: relative; /* 为了容纳绝对定位的图标 */
}

.selected-tags-container .dropdown-toggle-icon {
    margin-left: auto; /* 推到右边 */
     font-size: 0.8rem;
     color: #b0b0b0; /* Reverted icon color */
}


.dropdown-menu-custom {
  position: absolute;
  top: 100%; /* 位于输入框下方 */
  left: 0;
  z-index: 1000;
  min-width: 100%; /* 与触发器同宽 */
  max-height: 200px; /* 限制高度，出现滚动条 */
  overflow-y: auto;
  border: 1px solid #444; /* Reverted to dark border */
  border-radius: 0.25rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.175); /* Reverted shadow */
   background-color: #2c3e50; /* Reverted to dark background */
}

.dropdown-item-custom {
  padding: 0.25rem 1rem;
  cursor: pointer;
  color: #ecf0f1; /* Reverted to light text */
   display: flex; /* 使复选框和label对齐 */
   align-items: center;
}

.dropdown-item-custom label {
    cursor: pointer;
    margin-bottom: 0; /* 移除label默认margin */
    margin-left: 0.5rem; /* 复选框与label间隔 */
     flex-grow: 1; /* label占据剩余空间 */
}

.dropdown-item-custom:hover {
  background-color: #34495e; /* Reverted hover background color */
}

.analysis-area {
    background-color: #2c3e50; /* Reverted to dark background */
    color: #ecf0f1; /* Reverted to light text */
    border: 1px solid #34495e; /* Reverted to dark border */
    box-shadow: none; /* Removed shadow */
    text-align: left; /* Align text to the left */
}

.form-control-sm {
    height: calc(1.8125rem + 2px); /* 保持与按钮高度一致 */
    background-color: #242424; /* Ensure input background is dark */
    color: #e0e0e0; /* Ensure input text is light */
    border-color: #444; /* Ensure input border is dark */
}

/* Style for the calendar picker icon */
.form-control-sm::-webkit-calendar-picker-indicator {
    filter: invert(1) !important; /* Invert color to make it white */
}

.bg-dark {
  background-color: #1a1a1a !important; /* Reverted to dark background */
}

.text-light {
    color: #e0e0e0 !important; /* Reverted to light text */
}

.text-primary {
  color: #4fc3f7 !important; /* Reverted to teal */
}

.rounded {
    border-radius: 0.25rem !important;
}

.bg-secondary {
     background-color: #2c3e50 !important; /* Reverted to dark background */
}

.border-secondary {
    border-color: #444 !important; /* Reverted to dark border */
}

.btn-primary {
    background-color: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    background-color: #0056b3;
    border-color: #0056b3;
}

</style> 